﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace SimpleMVC.Filters
{
    public class CustomAuthorizeAttribute: AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            var principal = filterContext.HttpContext.User;
            if (principal != null)
            {
                var identity = principal.Identity;
                if (identity != null)
                {
                    bool unAuthorize = string.IsNullOrEmpty(Users) && string.IsNullOrEmpty(Roles);
                    if (unAuthorize)
                    {
                        return;
                    }
                    string[] users = null, roles = null;
                    if (!string.IsNullOrEmpty(Users))
                        users = Users.Split(',');
                    if (!string.IsNullOrEmpty(Roles))
                        roles = Roles.Split(',');
                    if (users != null && !string.IsNullOrEmpty(identity.Name))
                    {
                        foreach (var user in users)
                        {
                            if (string.Compare(identity.Name, user) == 0)
                            {
                                return;
                            }
                        }
                    }
                    if (roles != null)
                    {
                        foreach (var role in roles)
                        {
                            if (principal.IsInRole(role))
                            {
                                return;
                            }
                        }
                    }
                }
            }
            filterContext.Result = new HttpUnauthorizedResult("no authentication");
            
        }
    }
}